package com.xkcyy.one.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcyy.one.entity.Agent;
import com.xkcyy.one.entity.AgentCollaboration;
import com.xkcyy.one.exception.BusinessException;
import com.xkcyy.one.mapper.AgentCollaborationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 智能体协作关联服务类
 * 
 * @author yuand
 */
@Service
public class AgentCollaborationService {

    private final AgentCollaborationMapper agentCollaborationMapper;
    private final AgentService agentService;

    @Autowired
    public AgentCollaborationService(AgentCollaborationMapper agentCollaborationMapper, AgentService agentService) {
        this.agentCollaborationMapper = agentCollaborationMapper;
        this.agentService = agentService;
    }

    /**
     * 添加智能体协作关系
     *
     * @param agentId    主智能体ID
     * @param subAgentId 从智能体ID
     * @return 协作关系对象
     */
    public AgentCollaboration addCollaboration(Long agentId, Long subAgentId) {
        // 检查主智能体是否存在
        agentService.getAgentById(agentId);

        // 检查从智能体是否存在
        agentService.getAgentById(subAgentId);

        // 检查是否自关联
        if (agentId.equals(subAgentId)) {
            throw new BusinessException("不能与自己建立协作关系");
        }

        // 检查关联是否已存在
        LambdaQueryWrapper<AgentCollaboration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgentCollaboration::getAgentId, agentId)
                .eq(AgentCollaboration::getSubAgentId, subAgentId);
        if (agentCollaborationMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("协作关系已存在");
        }

        // 创建协作关系对象
        AgentCollaboration collaboration = new AgentCollaboration();
        collaboration.setAgentId(agentId);
        collaboration.setSubAgentId(subAgentId);

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        collaboration.setCreateTime(now);
        collaboration.setUpdateTime(now);

        // 插入协作关系
        agentCollaborationMapper.insert(collaboration);

        return collaboration;
    }

    /**
     * 批量添加协作关系
     *
     * @param agentId     主智能体ID
     * @param subAgentIds 从智能体ID列表
     * @return 添加的从智能体ID列表
     */
    @Transactional
    public List<Long> addCollaborations(Long agentId, List<Long> subAgentIds) {
        List<Long> addedSubAgentIds = new ArrayList<>();

        for (Long subAgentId : subAgentIds) {
            try {
                addCollaboration(agentId, subAgentId);
                addedSubAgentIds.add(subAgentId);
            } catch (BusinessException e) {
                // 如果关系已存在或智能体不存在，忽略错误，继续处理下一个
                continue;
            }
        }

        return addedSubAgentIds;
    }

    /**
     * 移除智能体协作关系
     *
     * @param agentId    主智能体ID
     * @param subAgentId 从智能体ID
     */
    public void removeCollaboration(Long agentId, Long subAgentId) {
        // 检查关联是否存在
        LambdaQueryWrapper<AgentCollaboration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgentCollaboration::getAgentId, agentId)
                .eq(AgentCollaboration::getSubAgentId, subAgentId);

        if (agentCollaborationMapper.selectCount(queryWrapper) == 0) {
            throw new BusinessException("协作关系不存在");
        }

        // 删除协作关系
        agentCollaborationMapper.delete(queryWrapper);
    }

    /**
     * 批量移除协作关系
     *
     * @param agentId     主智能体ID
     * @param subAgentIds 从智能体ID列表
     * @return 移除的从智能体ID列表
     */
    @Transactional
    public List<Long> removeCollaborations(Long agentId, List<Long> subAgentIds) {
        List<Long> removedSubAgentIds = new ArrayList<>();

        for (Long subAgentId : subAgentIds) {
            try {
                removeCollaboration(agentId, subAgentId);
                removedSubAgentIds.add(subAgentId);
            } catch (BusinessException e) {
                // 如果关系不存在，忽略错误，继续处理下一个
                continue;
            }
        }

        return removedSubAgentIds;
    }

    /**
     * 获取主智能体可协作的从智能体列表
     *
     * @param agentId 主智能体ID
     * @return 从智能体列表
     */
    public List<Agent> getSubAgentsByAgentId(Long agentId) {
        // 检查主智能体是否存在
        agentService.getAgentById(agentId);

        // 获取从智能体ID列表
        List<Long> subAgentIds = agentCollaborationMapper.selectSubAgentIdsByAgentId(agentId);

        if (subAgentIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取从智能体详情
        return subAgentIds.stream()
                .map(agentService::getAgentById)
                .collect(Collectors.toList());
    }

    /**
     * 获取可以使用从智能体的主智能体列表
     *
     * @param subAgentId 从智能体ID
     * @return 主智能体列表
     */
    public List<Agent> getAgentsBySubAgentId(Long subAgentId) {
        // 检查从智能体是否存在
        agentService.getAgentById(subAgentId);

        // 获取主智能体ID列表
        List<Long> agentIds = agentCollaborationMapper.selectAgentIdsBySubAgentId(subAgentId);

        if (agentIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取主智能体详情
        return agentIds.stream()
                .map(agentService::getAgentById)
                .collect(Collectors.toList());
    }

    /**
     * 清空主智能体的所有协作关系
     *
     * @param agentId 主智能体ID
     */
    public void clearAgentCollaborations(Long agentId) {
        // 检查主智能体是否存在
        agentService.getAgentById(agentId);

        // 删除主智能体的所有协作关系
        LambdaQueryWrapper<AgentCollaboration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgentCollaboration::getAgentId, agentId);
        agentCollaborationMapper.delete(queryWrapper);
    }
}